
package com.rt.schedulenew.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rt.schedulebase.dto.DictExamQueueDto;
import com.rt.schedulebase.dto.DictScheduleApmDto;
import com.rt.schedulebase.dto.DictUsersDto;
import com.rt.schedulebase.entity.DictScheduleApm;
import com.rt.schedulebase.entity.DictScheduleApmDuty;
import com.rt.schedulebase.entity.DictUsers;
import com.rt.schedulebase.mapper.DictExamQueueMapper;
import com.rt.schedulebase.mapper.DictScheduleApmDutyMapper;
import com.rt.schedulebase.mapper.DictScheduleApmMapper;
import com.rt.schedulenew.api.IDictScheduleApmService;
import com.rt.schedulenew.api.IDictUsersService;
import com.rt.schedulenew.dto.DictScheduleApmDutyDto;
import com.rt.schedulenew.utils.base.CommonUtil;
import com.rt.schedulenew.utils.util.DateUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class DictScheduleApmServiceImpl extends ServiceImpl<DictScheduleApmMapper, DictScheduleApm> implements IDictScheduleApmService {
    @Autowired
    private DictScheduleApmDutyMapper dictScheduleApmDutyMapper;
    @Autowired
    private DictExamQueueMapper dictExamQueueMapper;
    @Autowired
    private IDictUsersService dictUsersService;

    private static final String DATE_APM = "日期";
    private static final String WEEK_APM = "星期";
    private static final String COMMON_APM = "通用";

    /**
     * 获取 日期 时段
     *
     * @param dto
     * @return
     */
    @Override
    public List<DictScheduleApm> getDateScheduleApms(DictScheduleApmDto dto) {
        return getApmList(dto, DATE_APM);
    }

    /**
     * 获取 星期 时段
     *
     * @param dto
     * @return
     */
    @Override
    public List<DictScheduleApm> getWeekDateScheduleApms(DictScheduleApmDto dto) {
        return getApmList(dto, WEEK_APM);
    }

    /**
     * 获取通用时段号源
     *
     * @param dto
     * @return
     */
    @Override
    public List<DictScheduleApm> getNormalSchedule(DictScheduleApmDto dto) {
        return getApmList(dto, COMMON_APM);
    }

    private List<DictScheduleApm> getApmList(DictScheduleApmDto dto, String apmType) {
        QueryWrapper<DictScheduleApm> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getTimeStart()) && StringUtils.isNotBlank(dto.getTimeEnd())) {
            queryWrapper.eq("TIME_START", dto.getTimeStart());
            queryWrapper.eq("TIME_END", dto.getTimeEnd());
        } else if (StringUtils.isNotBlank(dto.getScheduleApm())) {
            queryWrapper.eq("SCHEDULE_APM", dto.getScheduleApm());
        }
        if (CollectionUtils.isNotEmpty(dto.getQueueNames())) {
            queryWrapper.in("QUEUE_NAME", dto.getQueueNames());
        }
        if (StringUtils.isNotBlank(dto.getApmFlag())) {
            queryWrapper.eq("APM_FLAG", dto.getApmFlag());
        }
        if (StringUtils.isNotBlank(dto.getScheduleDate())) {
            if (DATE_APM.equals(apmType)) {
                if (StringUtils.isNotBlank(dto.getScheduleDate())) {
                    queryWrapper.eq("SCHEDULE_DATE", dto.getScheduleDate());
                }
                queryWrapper.isNull("WEEK_DATE");
            } else if (WEEK_APM.equals(apmType)) {
                if (StringUtils.isNotBlank(dto.getWeekDate())) {
                    queryWrapper.eq("WEEK_DATE", dto.getWeekDate());
                }
                queryWrapper.isNull("SCHEDULE_DATE");
            } else if (COMMON_APM.equals(apmType)) {
                queryWrapper.isNull("SCHEDULE_DATE");
                queryWrapper.isNull("WEEK_DATE");
            }
        }
        queryWrapper.ne("STOP_FLAG", "2");
        queryWrapper.isNull("APM_TYPE");
        queryWrapper.orderByAsc("TIME_START", "QUEUE_NAME");
        List<DictScheduleApm> dictScheduleApmList = baseMapper.selectList(queryWrapper);
        // 过滤掉 日期范围外的时段
        if (CollectionUtils.isNotEmpty(dictScheduleApmList) && StringUtils.isNotBlank(dto.getScheduleDate())) {
            Iterator<DictScheduleApm> it = dictScheduleApmList.iterator();
            while (it.hasNext()) {
                DictScheduleApm dsa = it.next();
                if (dsa.getDateStart() != null && dsa.getDateEnd() != null) {
                    String apm = dto.getScheduleDate();
                    if (dsa.getDateStart().length() == 5) {
                        apm = apm.substring(5);
                    }
                    if (apm.compareTo(dsa.getDateStart()) >= 0 && apm.compareTo(dsa.getDateEnd()) <= 0) {
                        continue;
                    }
                    if (dsa.getDateEnd().compareTo(dsa.getDateStart()) < 0 && apm.compareTo(dsa.getDateStart()) <= 0 && apm.compareTo(dsa.getDateEnd()) <= 0) {
                        continue;
                    }
                    if (dsa.getDateEnd().compareTo(dsa.getDateStart()) < 0 && apm.compareTo(dsa.getDateStart()) >= 0 && apm.compareTo(dsa.getDateEnd()) >= 0) {
                        continue;
                    }
                    it.remove();
                }
            }
        }
        return dictScheduleApmList;
    }

    @Override
    public List<DictScheduleApmDto> getScheduleApms(DictScheduleApmDto dto) {
        // 根据时间段获取时间段的相同的时段信息
        List<DictScheduleApmDto> dictScheduleApmDtoList = baseMapper.getScheduleApms(dto);
        if (CollectionUtils.isNotEmpty(dictScheduleApmDtoList) && StringUtils.isNotBlank(dto.getScheduleDate())) {
            Iterator<DictScheduleApmDto> it = dictScheduleApmDtoList.iterator();
            while (it.hasNext()) {
                DictScheduleApm dsa = it.next();
                if (dsa.getDateStart() != null && dsa.getDateEnd() != null) {
                    String scheduleDate = dto.getScheduleDate();
                    if (dsa.getDateStart().length() == 5) {
                        scheduleDate = scheduleDate.substring(5);
                    }
                    // 判断号源周期是否付符合，如果不符合就删除
                    if (scheduleDate.compareTo(dsa.getDateStart()) >= 0 && scheduleDate.compareTo(dsa.getDateEnd()) <= 0) {
                        continue;
                    }
                    if (dsa.getDateEnd().compareTo(dsa.getDateStart()) < 0
                            && scheduleDate.compareTo(dsa.getDateStart()) <= 0
                            && scheduleDate.compareTo(dsa.getDateEnd()) <= 0) {
                        continue;
                    }
                    if (dsa.getDateEnd().compareTo(dsa.getDateStart()) < 0
                            && scheduleDate.compareTo(dsa.getDateStart()) >= 0
                            && scheduleDate.compareTo(dsa.getDateEnd()) >= 0) {
                        continue;
                    }
                    it.remove();
                }
            }
        }
        return dictScheduleApmDtoList;
    }

    @Override
    public DictScheduleApm selectOne(DictScheduleApmDto dto, String apmType) {
        if (StringUtils.isNotBlank(dto.getQueueName())) {
            dto.setQueueNames(CommonUtil.split2List(dto.getQueueName()));
        }
        dto.setWeekDate(DateUtil.getWeek(dto.getScheduleDate()));
        List<DictScheduleApm> apmList = getApmList(dto, apmType);
        if (apmList != null && !apmList.isEmpty()) {
            return apmList.get(0);
        }
        return null;
    }

    @Override
    public DictScheduleApm selectOneByApmCode(String apmCode) {
        QueryWrapper<DictScheduleApm> query = new QueryWrapper<>();
        query.eq("APM_CODE", apmCode);
        return baseMapper.selectOne(query);
    }

    @Override
    public List<DictScheduleApmDto> getDutyApms(DictScheduleApmDto dictScheduleApmDto) {
        return baseMapper.getCommonScheduleApm(dictScheduleApmDto);
    }

    @Override
    public List<String> getScheduleApm(DictScheduleApmDto dto) {
        List<String> apmList;
        if (StringUtils.isBlank(dto.getScheduleApm()) && CollectionUtils.isEmpty(dto.getQueueNames())) {
            apmList = null;
        } else {
            apmList = baseMapper.getScheduleApm(dto);
        }
        return apmList;
    }

    @Override
    public List<DictUsers> getApmStaffName(DictScheduleApmDto dictScheduleApmDto) {
        List<DictUsers> lsStaffName = new ArrayList<>();

        DictExamQueueDto dictExamQueueDto = new DictExamQueueDto();
        dictExamQueueDto.setClassAttr(dictScheduleApmDto.getClassAttr());
        dictExamQueueDto.setUseFlag("0");
        dictExamQueueDto.setHospitalCode(dictScheduleApmDto.getHospitalCode());
        dictExamQueueDto.setExamClass(dictScheduleApmDto.getExamClass());
        List<DictExamQueueDto> queues = dictExamQueueMapper.getQueueList(dictExamQueueDto);

        if (CollectionUtils.isEmpty(queues)) {
            return lsStaffName;
        }

        String expireDayeMax = DateUtil.getCurrDateStr();
        for (DictExamQueueDto queue : queues) {
            if (queue.getExpireDays() == null) {
                expireDayeMax = null;
                break;
            }
            String expireDate = DateUtil.date2Str(DateUtil.dateAdd(new Date(), queue.getExpireDays() - 1), DateUtil.FORMAT_DATE);
            if (expireDate.compareTo(expireDayeMax) <= 0) {
                continue;
            }
            expireDayeMax = expireDate;
        }
        DictScheduleApmDutyDto dictScheduleApmDutyDto = new DictScheduleApmDutyDto();
        dictScheduleApmDutyDto.setStartDate(DateUtil.getCurrDateStr());
        dictScheduleApmDutyDto.setEndDate(expireDayeMax);
        dictScheduleApmDutyDto.setQueues(queues);
        List<DictScheduleApmDuty> lsDuty = dictScheduleApmDutyMapper.getDutyList(dictScheduleApmDutyDto);
        List<String> tempStaffName = new ArrayList<>();
        for (DictScheduleApmDuty duty : lsDuty) {
            if (duty.getStaffName() != null && !tempStaffName.contains(duty.getStaffName())) {
                DictUsers dictUsers = new DictUsers();
                dictUsers.setName(duty.getStaffName());
                lsStaffName.add(dictUsers);
                tempStaffName.add(duty.getStaffName());
            }
        }
        DictUsersDto dictUsersDto = new DictUsersDto();
        dictUsersDto.setStaffType("0");
        List<DictUsers> lsDictUsers = dictUsersService.getList(dictUsersDto);
        for (DictUsers du : lsStaffName) {
            for (DictUsers dictUsers2 : lsDictUsers) {
                if (dictUsers2.getName().equals(du.getName())) {
                    du.setIntroduce(dictUsers2.getIntroduce());
                    break;
                }
            }
        }
        return lsStaffName;
    }

    @Override
    public List<DictScheduleApm> getList(DictScheduleApmDto dto) {
        QueryWrapper<DictScheduleApm> wrapper = new QueryWrapper<>();
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("DATE_START", dto.getDateStart());
        hashMap.put("DATE_END", dto.getDateEnd());
        hashMap.put("TIME_END", dto.getTimeEnd());
        hashMap.put("TIME_START", dto.getTimeStart());
        hashMap.put("MERGE_APM_CODE", dto.getMergeApmCode());
        String queueName = dto.getQueueName();
        List<String> stringList = CommonUtil.split2List(queueName);
        if (stringList != null && stringList.size() > 1) {
            wrapper.in("QUEUE_NAME", stringList);
        } else {
            hashMap.put("QUEUE_NAME", queueName);
        }
        List<String> apmCodes = dto.getApmCodes();
        if (apmCodes != null && apmCodes.size() > 0) {
            wrapper.in("APM_CODE", apmCodes);
        }
        wrapper.isNull("WEEK_DATE");
        wrapper.isNull("SCHEDULE_DATE");
        wrapper.allEq(hashMap, false);
        wrapper.orderByAsc("TIME_START");
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<DictScheduleApm> getScheduleByApmCode(DictScheduleApmDto dto) {
        QueryWrapper<DictScheduleApm> qw = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        List<String> apmCodes = dto.getApmCodes();
        if (apmCodes != null && apmCodes.size() > 0) {
            qw.in("APM_CODE", apmCodes);
        }
        qw.allEq(map, false);
        return baseMapper.selectList(qw);
    }

    @Override
    public List<DictScheduleApm> getScheduleByMergeApmCode(DictScheduleApmDto apmDto) {
        QueryWrapper<DictScheduleApm> qw = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        map.put("MERGE_APM_CODE", apmDto.getMergeApmCode());
        map.put("TIME_START", apmDto.getTimeStart());
        map.put("TIME_END", apmDto.getTimeEnd());
        map.put("WEEK_DATE", apmDto.getWeekDate());
        map.put("SCHEDULE_DATE", apmDto.getScheduleDate());
        qw.allEq(map, false);
        return baseMapper.selectList(qw);
    }

    @Override
    public DictScheduleApm getBigSchedule(DictScheduleApm dictScheduleApm) {
        QueryWrapper<DictScheduleApm> wrapper = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("QUEUE_NAME", dictScheduleApm.getQueueName());
        map.put("DATE_END", dictScheduleApm.getDateEnd());
        map.put("DATE_START", dictScheduleApm.getDateStart());
        map.put("APM_TYPE", "1");
        String timeEnd = dictScheduleApm.getTimeEnd();
        String timeStart = dictScheduleApm.getTimeStart();
        if (StringUtils.isNotBlank(timeEnd)) {
            wrapper.ge("TIME_END", timeEnd);
        }
        if (StringUtils.isNotBlank(timeStart)) {
            wrapper.le("TIME_START", timeStart);
        }
        String weekDate = dictScheduleApm.getWeekDate();
        if (StringUtils.isNotBlank(weekDate)) {
            map.put("WEEK_DATE", weekDate);
        } else {
            wrapper.isNull("WEEK_DATE");
        }
        String scheduleDate = dictScheduleApm.getScheduleDate();
        if (StringUtils.isNotBlank(scheduleDate)) {
            map.put("SCHEDULE_DATE", scheduleDate);
        } else {
            wrapper.isNull("SCHEDULE_DATE");
        }
        wrapper.allEq(map, false);
        List<DictScheduleApm> dictScheduleApms = baseMapper.selectList(wrapper);
        if (dictScheduleApms == null || dictScheduleApms.size() == 0) {
            return null;
        }
        return dictScheduleApms.get(0);
    }

    @Override
    public void updateTsak(DictScheduleApm dictScheduleApm) {
        baseMapper.updateTsak(dictScheduleApm);
    }

    public DictScheduleApm getInfo(DictScheduleApmDto dto) {
        QueryWrapper<DictScheduleApm> qw = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        map.put("APM_CODE", dto.getApmCode());
        map.put("DATE_START", dto.getDateStart());
        map.put("DATE_END", dto.getDateEnd());
        map.put("TIME_START", dto.getTimeStart());
        map.put("TIME_END", dto.getTimeEnd());
        map.put("QUEUE_NAME", dto.getQueueName());
        map.put("SCHEDULE_DATE", dto.getScheduleDate());
        map.put("WEEK_DATE", dto.getWeekDate());
        if (StringUtils.isNotBlank(dto.getStopFlag())) {
            map.put("STOP_FLAG", dto.getStopFlag());
        }
        if (StringUtils.isBlank(dto.getScheduleDate()) && StringUtils.isBlank(dto.getWeekDate())) {
            qw.isNull("SCHEDULE_DATE");
            qw.isNull("WEEK_DATE");
        }
        qw.allEq(map, false);
        return baseMapper.selectOne(qw);
    }
}
